#!/usr/bin/python




import threading

from killable_thread import KThread
# We use the KThreads in order to be able to delete it. Though, this "hacked" version of threads makes the execution a bit slower. Thus when an official version of killable thread is released, it should be comparedwith KThread and likely used instead of it.

import logging
logger = logging.getLogger("followed_thread")




class FollowedThread:

############################################################
	
	def __init__(self, window, thread_name, thread_method, thread_method_args, ending_method):
		
		logger.debug("init()")
		
		self.window = window
		self.name = thread_name
		self.method = thread_method
		self.method_args = thread_method_args
		self.ending_method = ending_method
		
		self.timeout_id = None

############################################################

	def run(self):
		
		logger.debug("run()")
		
		# Run the tread that builds the list of "other elements"
		logger.debug("starting new "+self.name)
		t = KThread(name=self.name, target=self.method, args=self.method_args)
		# t = KThread(name=THREAD_PROPS, target=getOtherElements, args=(property_uri,))
		t.start()
		
		self.timeout_id = self.window.setTimeout(500, self.refresh)

############################################################

	def kill(self):
		
		logger.debug("kill(%s)" % self)
		
		if self.timeout_id == None:
			return 1
		
		# Clear the associated timeout so that the thread will not be considered finished.
		logger.debug("\tclearing timeout")
		self.window.clearTimeout(self.timeout_id)
		self.timeout_id = None
		
		# Kill thread_name.
		threads = threading.enumerate()
		logger.debug("threads = "+str(threads))
		for thread in threads:
			if thread.getName() == self.name:
				"""
				if thread.killed:
					# thread_name was running, has already been killed, but is still running (latency).
					return
				"""
				logger.debug("thread = "+str(thread)+" still running, is going to be killed.")
				thread.kill()
		
		# Wait for thread_name to be actually finished!!!
		while (True):
			
			thread_props_finished = True
			threads = threading.enumerate()
			for thread in threads:
				if thread.getName() == self.name:
					thread_props_finished = False
					continue
			
			logger.debug("%s really finished!" % self.name)
			break # while loop when the thread has really been killed.

############################################################

	def refresh(self, arg2):
		
		logger.debug("refresh(%s, %s)" % (self, arg2))
		
		# Check whether thread_name is still running.
		threads = threading.enumerate()
		for thread in threads:
			if thread.getName() == self.name:
				# thread_name is still running.
				self.timeout_id = self.window.setTimeout(500, self.refresh)
				return
		
		logger.debug(self.name + " has ended, calling its ending method.")
		self.ending_method()















